package com.langxin.erp.core.interceptor;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.perf4j.StopWatch;
import org.perf4j.log4j.Log4JStopWatch;
import org.slf4j.Logger;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
 * 日志拦截器用于查看请求信息
 *
 * Date: 2015/1/19
 * Time: 15:12
 */

public class LogSpringActionHandler extends HandlerInterceptorAdapter {

    private Logger log = org.slf4j.LoggerFactory.getLogger(LogSpringActionHandler.class);

    private StopWatch stopWatch = null;

    private String action= "";

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        if(log.isInfoEnabled()){
            action = request.getRequestURL().toString();
            Map map = request.getParameterMap();
            StringBuilder  buf = new StringBuilder();
           for (Object key :map.keySet()){
             buf.append(key).append("=").append(request.getParameter(key.toString())).append("&");
           }
            log.info(action+"?"+buf.toString());
            this.stopWatch = new Log4JStopWatch();
        }
        return true;
    }


    @Override
    public void postHandle(
            HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
            throws Exception{
		if(log.isInfoEnabled()){
            stopWatch.stop(this.action);
		}
        super.postHandle(request, response, handler, modelAndView);
    }

}
